package com.example;

import com.alibaba.fastjson.JSONObject;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import java.util.List;

public class ExampleMain {
    static EntityManagerFactory emf = Persistence.createEntityManagerFactory("my-persistence-unit");
    public static void main(String[] args) {
        Integer id = persistPerson();
        Person person = loadPersonById(id);
        List<Phone> phones = mergeAndGetPhones(person);
        System.err.println(JSONObject.toJSONString(phones,true));
        emf.close();
    }
    private static List<Phone> mergeAndGetPhones(Person person){
        EntityManager em = emf.createEntityManager();
        person = em.merge(person);
        System.err.println(JSONObject.toJSONString(person,true));
        List<Phone> phones = person.getPhones();
        em.close();
        return phones;
    }
    private static Person loadPersonById(Integer id){
        EntityManager em = emf.createEntityManager();
        Person person = em.find(Person.class,id);
        em.close();
        return person;
    }
    private static Integer persistPerson(){
        Person person = new Person();
        person.setName("Jackie");
        person.addPhone("111-11-1111","Cell");
        person.addPhone("222-22-2222","Work");
        EntityManager em = emf.createEntityManager();
        em.getTransaction().begin();
        em.persist(person);
        em.getTransaction().commit();
        em.close();
        return person.getId();
    }
}
